package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.MenuManagementDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.MenuManagement;
import com.itheima.health.service.MenuManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class MenuManagementServiceImpl implements MenuManagementService {

    //依赖注入
    @Autowired
    private MenuManagementDao menuManagementDao;

    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {

        /**
         * 使用分页插件PageHelper
         * 参数1: 起始页 1
         * 参数2: 每页数量 10
         */
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //调用dao, 获取菜单数据
        Page<MenuManagement> page = menuManagementDao.selectByCondition(queryPageBean.getQueryString());
        //创建PageResult结果对象( 菜单的总记录数, 当前页显示需要的10条菜单数据 )
        return new PageResult(page.getTotal(), page.getResult());
    }

    //添加菜单
    @Override
    public void add(MenuManagement menuManagement,String username) {
        //调用dao中, 添加菜单
        menuManagementDao.add(menuManagement);
        //查询用户名对应的id
        Integer role_id=menuManagementDao.findIdByUserName(username);
        //封装到map集合中保存到中间表
        Map<String, Integer> map = new HashMap<>();
        map.put("role_id",role_id);
        map.put("menu_id",menuManagement.getId());
        menuManagementDao.addRole_Menu(map);
        }



    /**
     * 删除菜单
     * @param id
     */
    @Override
    public void deleteById(Integer id,String username) {
        //通过菜单ID, 去中间表中查询该菜单的权限信息
        Long count = menuManagementDao.countMenuManagementById(id);

        Long counts = (Long) menuManagementDao.findUserId(username);
        if (count != counts){
            //说明权限对应不上
            throw new RuntimeException("权限不足，不能删除");
        }
        //说明 权限对应上可以删除
        //删除中间表
        menuManagementDao.deleteRole_Menu(id);
        menuManagementDao.deleteById(id);
    }

    /**
     * 根据ID 查询菜单
     * @param id 菜单ID
     * @return
     */
    @Override
    public MenuManagement findById(Integer id) {
        //调用Dao层的findById的方法, 获取到菜单
        return menuManagementDao.findById(id);
    }

    /**
     * 编辑菜单
     * @param menuManagement 需要更新的菜单对象
     */
    @Override
    public void edit(MenuManagement menuManagement) {
        //调用Dao层的edit的方法, 获取到菜单
        menuManagementDao.edit(menuManagement);
    }

    /**
     * 查询所有菜单
     * @return
     */
    @Override
    public List<MenuManagement> findAll() {
        //调用dao层的findAll方法, 获取所有的菜单
        return menuManagementDao.findAll();
    }
}
